package cn.yogehaoren.service.impl;

import cn.yogehaoren.dao.ProxyClientMapper;
import cn.yogehaoren.model.ProxyClient;
import cn.yogehaoren.service.ProxyClientService;
import cn.yogehaoren.utils.SqlSessionManager;
import com.haojiangbo.config.ClientCheckConfig;
import com.haojiangbo.model.ConfigModel;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;


/**
 * @author WangNing yogehaoren@gamil.com <br>
 * @since 1.0
 */
public class ProxyClientServiceImpl implements ProxyClientService {

    @Override
    public List<ConfigModel> reloadConfigModel() {
        try(SqlSession sqlSession = SqlSessionManager.getSqlSession()){
            ProxyClientMapper proxyClientMapper = SqlSessionManager.getMapper(sqlSession, ProxyClientMapper.class);

            List<ProxyClient> allProxyClients = proxyClientMapper.getAllProxyClients();

            List<ConfigModel> configModels = new ArrayList<>();
            synchronized (ClientCheckConfig.class){
                ClientCheckConfig.CLIENT_CHECK_MAP.clear();
                allProxyClients.forEach(proxyClient -> {

                    ConfigModel configModel = new ConfigModel();
                    configModel.setClientId(proxyClient.getClientId());
                    configModel.setPort(proxyClient.getLocalPort());
                    configModel.setClientUrl(String.format("%s:%d", proxyClient.getClientHost(), proxyClient.getClientPort()));
                    configModels.add(configModel);
                    ClientCheckConfig.CLIENT_CHECK_MAP.put(proxyClient.getClientId(), configModel);

                });
            }


            return configModels;

        }

    }

    private ProxyClientServiceImpl(){

    }

    private static ProxyClientServiceImpl INSTANCE = null;

    public static ProxyClientService getInstance(){
        if(INSTANCE == null){
            synchronized (ProxyClientServiceImpl.class){
                if(INSTANCE == null){
                    INSTANCE = new ProxyClientServiceImpl();
                }
            }
        }
        return INSTANCE;
    }
}
